'''
Created on Apr 19, 2009

@author: Administrator
'''
from django.contrib import auth
from django.forms import forms
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from com.ericyang.common.web import redirect, page404, response
from com.ericyang.common.web.middleware import threadlocals
from com.ericyang.groupshopping.addressbook.models import  AddressBook
from com.ericyang.groupshopping.addressbook.forms import AddressBookCreationForm, AddressBookChangeForm

# create address book
@login_required
def createAddressBook(request):
    user = threadlocals.get_current_user()
    username = user.username
    if request.method == 'POST':
        form = AddressBookCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            return redirect("/addressbook/list/")
    else :
        form = AddressBookCreationForm()
    
    return response('addressbook/addressbook_edit.html', {'form':form, 'user':user})

# edit a address book
@login_required
def editAddressBook(request, book_id):
    user = threadlocals.get_current_user()
    addressbook_id = int(book_id)
    book = get_object_or_404(AddressBook, pk=addressbook_id)
    if request.method == 'POST':
        form = AddressBookChangeForm(book, request.POST)
        if form.is_valid():
            user = form.save()
            return redirect("/addressbook/list/")
    else :
        args = {'name': book.name,
               'phone': book.phone,
               'email': book.email,
               'address': book.address,
               'postnum': book.postnum,
               'province': book.province,
               'city': book.city,
               'district': book.district }
        form = AddressBookChangeForm(book, args)
    
    return response('addressbook/addressbook_edit.html', {'form':form, 'user':user})

# list user's address books
@login_required
def list_AddressBook(request):
    user = threadlocals.get_current_user()
    user_id = user.id
    addressbooks = AddressBook.objects.filter(user__id=user_id)
    return response('addressbook/addressbook_list.html', {'addressbooks':addressbooks})


# list user's address books
@login_required
def delete_AddressBook(request, book_id):
    user = threadlocals.get_current_user()
    user_id = user.id
    addressbook_id = int(book_id)
    addressbook = get_object_or_404(AddressBook, pk=addressbook_id)
    if addressbook.user.id == user_id:
        addressbook.delete()
    return redirect("/addressbook/list/")


